package com.wyh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easemob.im.server.EMService;
import com.easemob.im.server.model.EMMessage;
import com.easemob.im.server.model.EMUser;
import com.easemob.im.shaded.reactor.core.publisher.Mono;
import com.wyh.common.response.PageInfo;
import com.wyh.common.result.R;
import com.wyh.common.util.SnowUtil;
import com.wyh.entity.*;
import com.wyh.mapper.*;
import com.wyh.request.AddChatRoomVerifyMessageRequest;
import com.wyh.request.AddFriendVerifyMessageRequest;
import com.wyh.request.MsgVerifyMessageRequest;
import com.wyh.service.IAdminBlackListService;
import com.wyh.service.IMsgChatRoomService;
import com.wyh.service.IMsgRecontactService;
import com.wyh.service.IMsgVerifyMessageService;
import com.wyh.vo.AddFriendVo;
import com.wyh.vo.VerifyMessageVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【请填写功能名称】业务层处理
 *
 * @author WangYuHang
 * @date 2024-03-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class MsgVerifyMessageServiceImpl implements IMsgVerifyMessageService {

    private final MsgVerifyMessageMapper baseMapper;

    private final AdminUserMapper adminUserMapper;

    private AdminUserServiceImpl adminUserService;

    @Autowired
    private IMsgChatRoomService msgChatRoomService;
    @Autowired
    private IAdminBlackListService adminBlackListService;


    @Autowired
    private IMsgRecontactService msgRecontactService;

    @Autowired
    private final EMService emService;

    private final SnowUtil snowUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgVerifyMessage add(MsgVerifyMessageRequest request) {
        MsgVerifyMessage entity = MsgVerifyMessage.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }




    @Override
    public R<String> addFriendVerifyMessage(AddFriendVerifyMessageRequest messageRequest) {
        if (!StringUtils.isNotBlank(messageRequest.getApplyId())  || !StringUtils.isNotBlank(messageRequest.getUserId())){
            return R.error("参数错误");
        }
        //模拟当前用户为666666
        String userId = "666666";
        //好友申请逻辑

        //判断是否被拉黑
        if (adminBlackListService.isBlack(messageRequest.getApplyId(), messageRequest.getUserId())) {
            R.error("你已经被对方拉黑，无法添加对方为好友！");
        }


        //2.判断是否已经是好友  如果是 无需重复添加
        if (msgRecontactService.isFriend(messageRequest.getApplyId(), messageRequest.getUserId())) {
            R.error("对方已经是你的好友 无需添加！");
        }


        //3.判断是否已经超出好友上限
        if (msgRecontactService.isOutFriendMax(messageRequest.getApplyId())){
            return R.error("好友超出上限！");
        }


        //4.发送验证消息
        MsgVerifyMessage build = MsgVerifyMessage.builder()
                //验证消息类型 0为好友验证信息
                .type(0)
                //申请人id
                .applyId(messageRequest.getApplyId())
                //用户id
                .userId(messageRequest.getUserId())
                //申请备注
                .applyRemark(messageRequest.getApplyRemark())
                //申请内容
                .applyContent(messageRequest.getApplyContent())
                //申请状态 0验证中 1同意 2拒绝
                .verifyStatus(0)
                .build();

        baseMapper.insert(build);
        return R.success("验证消息发送成功！");
    }

    @Override
    public R<String> addChatRoomVerifyMessage(AddChatRoomVerifyMessageRequest messageRequest) {
        //模拟当前用户为666666
        String userId= "666666";

        //判断群成员是否已满
        if (msgChatRoomService.queryIsMax(messageRequest.getChatRoomId())){
            return R.error("群成员已满！");
        }

        //判断自己是否已在群里
        if (msgChatRoomService.queryIsExist(messageRequest.getApplyId(), messageRequest.getChatRoomId())){
            return R.error("你已经在群里,无需申请加入");
        }

        //添加加群申请
        //3.发送验证消息
        MsgVerifyMessage build = MsgVerifyMessage.builder()
                //验证消息类型
                .type(1)
                //申请人id
                .applyId(messageRequest.getApplyId())
                //群id
                .chatRoomId(messageRequest.getChatRoomId())
                //申请备注
                .applyRemark(messageRequest.getApplyRemark())
                //申请内容
                .applyContent(messageRequest.getApplyContent())
                //申请状态 0验证中 1同意 2拒绝
                .verifyStatus(0)
                .build();
        baseMapper.insert(build);
        return R.success("加群申请已发送！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Integer> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(MsgVerifyMessageRequest request) {
        MsgVerifyMessage entity = MsgVerifyMessage.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0 ;
    }

    @Override
    public MsgVerifyMessage getById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<MsgVerifyMessage> pageList(MsgVerifyMessageRequest request) {
        Page<MsgVerifyMessage> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<MsgVerifyMessage> query = this.buildWrapper(request);
        IPage<MsgVerifyMessage> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    /**
     * 处理验证消息
     * @param msgVerifyMessageRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized R<String> disposeVerifyMessage(MsgVerifyMessageRequest msgVerifyMessageRequest) {
        MsgVerifyMessage build = MsgVerifyMessage.builder().build();
        BeanUtils.copyProperties(msgVerifyMessageRequest,build);
        //通过条件更新 验证消息的状态 0 1 2
        baseMapper.update(build,Wrappers.lambdaQuery(MsgVerifyMessage.class).eq(MsgVerifyMessage::getApplyId,msgVerifyMessageRequest.getApplyId())
                .eq(MsgVerifyMessage::getUserId,msgVerifyMessageRequest.getUserId()));


            //同意添加好友 或群
            if (msgVerifyMessageRequest.getVerifyStatus()==1){

                //0类型 处理好友验证消息
                if (msgVerifyMessageRequest.getType()==0){

                //判断好友是否超出上限
                if (msgRecontactService.isOutFriendMax(msgVerifyMessageRequest.getApplyId())){
                      R.error("好友数量已经达到上限");
                }
                AdminUser friendUser = adminUserService.getById(msgVerifyMessageRequest.getUserId());

                MsgRecontact build1 = MsgRecontact.builder()
                        .userId(msgVerifyMessageRequest.getApplyId())
                        .friendId(msgVerifyMessageRequest.getUserId())
                        .remark(msgVerifyMessageRequest.getApplyRemark())
                        .nickName(friendUser.getNickname())
                        .avatar(friendUser.getHeadImage())
                        .build();
                msgRecontactService.add(build1);
                R.success("添加好友成功！");
                }

                //1处理加群验证消息
                if(msgVerifyMessageRequest.getType()==1){

                    //判断群成员是否已满
                    if (msgChatRoomService.queryIsMax(msgVerifyMessageRequest.getChatRoomId())){
                        R.error("群成员已满！");
                    }

                    //判断是否在群里
                    if (msgChatRoomService.queryIsExist(msgVerifyMessageRequest.getApplyId(), msgVerifyMessageRequest.getChatRoomId())){
                        R.error("已经在群里,无需添加");
                    }

                    //添加新成员
                    msgChatRoomService.addPerson(msgVerifyMessageRequest.getChatRoomId(), msgVerifyMessageRequest.getApplyId());
                    R.success("加群成功！");
                }

            }
        return R.success("处理成功！");
    }

    @Override
    public R<List<VerifyMessageVo>> getVerifyMessage() {
        //通过请求头 获取token信息
        //并获取当前用户的id 此时当id=666666
        String userId= "666666";

        List<MsgVerifyMessage> msgVerifyMessages = baseMapper.selectList(Wrappers.lambdaQuery(MsgVerifyMessage.class).eq(MsgVerifyMessage::getUserId, userId));

        List<VerifyMessageVo> list = new ArrayList<>();

        VerifyMessageVo verifyMessageVo = null;

        for (MsgVerifyMessage msgVerifyMessage : msgVerifyMessages) {
            if (msgVerifyMessage.getType()==0){
                //好友申请消息
                AdminUser adminUser = adminUserService.getById(msgVerifyMessage.getApplyId());
                //消息类型 0好友申请  1群申请
                verifyMessageVo.setType(0);
                //用户id
                verifyMessageVo.setUserId(adminUser.getUserId());
                //内容设置
                verifyMessageVo.setContent(msgVerifyMessage.getApplyContent());
                //昵称设置
                verifyMessageVo.setNickName(adminUser.getNickname());
                //头像设置
                verifyMessageVo.setHeaderImg(adminUser.getHeadImage());
                //是否是群里添加
                verifyMessageVo.setIsGroupInvite(msgVerifyMessage.getIsGroupInvite());
                //验证状态设置
                verifyMessageVo.setVerifyStatus(msgVerifyMessage.getVerifyStatus());
                list.add(verifyMessageVo);
            }
            if (msgVerifyMessage.getType()==1){
                //群聊邀请消息
                MsgChatRoom msgChatRoom = msgChatRoomService.getById(msgVerifyMessage.getChatRoomId());
                verifyMessageVo.setType(1);
                verifyMessageVo.setChatRoomHeaderImg(msgChatRoom.getChatRoomAvatar());
                verifyMessageVo.setContent(msgVerifyMessage.getApplyContent());
                verifyMessageVo.setChatRoomName(msgChatRoom.getChatRoomNick());
                //验证状态设置
                verifyMessageVo.setVerifyStatus(msgVerifyMessage.getVerifyStatus());
                list.add(verifyMessageVo);
            }
        }
        return  R.success(list);
    }

    @Override
    public List<MsgVerifyMessage> list(MsgVerifyMessageRequest request) {
        LambdaQueryWrapper<MsgVerifyMessage> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<MsgVerifyMessage> buildWrapper(MsgVerifyMessageRequest param) {
        LambdaQueryWrapper<MsgVerifyMessage> query = new LambdaQueryWrapper<>();
         if (StringUtils.isNotBlank(param.getApplyId())){
               query.like(MsgVerifyMessage::getApplyId ,param.getApplyId());
        }
         if (StringUtils.isNotBlank(param.getUserId())){
               query.like(MsgVerifyMessage::getUserId ,param.getUserId());
        }
         if (StringUtils.isNotBlank(param.getApplyRemark())){
               query.like(MsgVerifyMessage::getApplyRemark ,param.getApplyRemark());
        }
        if (param.getIsDelete() != null){
               query.eq(MsgVerifyMessage::getIsDelete ,param.getIsDelete());
        }
         if (StringUtils.isNotBlank(param.getCreateUserId())){
               query.like(MsgVerifyMessage::getCreateUserId ,param.getCreateUserId());
        }
         if (StringUtils.isNotBlank(param.getUpdateUserId())){
               query.like(MsgVerifyMessage::getUpdateUserId ,param.getUpdateUserId());
        }
        return query;
    }

}
